package com.smartphone.ui;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.opengl.GLSurfaceView;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.Surface;
import android.view.SurfaceView;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.TextView;

import com.smartphone.R;
import com.smartphone.cmd.CmdInfo;
import com.smartphone.core.Smartphone;
import com.smartphone.core.SmartphoneState;

import org.linphone.mediastream.video.AndroidVideoWindowImpl;
import org.linphone.mediastream.video.capture.hwconf.AndroidCameraConfiguration;

import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;


public class CallActivity extends AppCompatActivity implements View.OnClickListener {
    private static final String TAG = "CallActivity";
    private SurfaceView remoteview = null;
    private SurfaceView localview = null;
    private AndroidVideoWindowImpl mVideoWindow = null;
    private CallReceiver mCallReceiver = null;

    private Smartphone sp = null;
    private TextView tvUsername = null;
    private TextView tvTime = null;
    private ImageButton btnHunghp = null;
    private ImageButton btnHome = null;
    private int timerCount = 0;
    private Handler timerHandler = new Handler();
    private Runnable timerRunnable = new Runnable() {
        public void run() {
            timerCount++;
            timerHandler.postDelayed(this, 1000);
            tvTime.setText(format(timerCount));
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD |
                WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED |
                WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON |
                WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        sp = Smartphone.getInstance(); sp = Smartphone.getInstance();
        IntentFilter filter = new IntentFilter();
        filter.addAction(Smartphone.BroadcastCall);
        mCallReceiver = new CallReceiver();
        this.registerReceiver(mCallReceiver, filter);

        boolean video = sp.callVideoEnabled(sp.getCurrentCallid());
        if (!video) {
            setContentView(R.layout.activity_call_audio);

        } else {
            setContentView(R.layout.activity_call_video);
            remoteview = (SurfaceView) findViewById(R.id.remotevideo);
            localview = (SurfaceView) findViewById(R.id.localvideo);
            remoteview.setZOrderOnTop(true);
            remoteview.setZOrderOnTop(false);
            localview.setZOrderOnTop(false);
            localview.setZOrderMediaOverlay(true);
            btnHome = (ImageButton) findViewById(R.id.btnHome);
            btnHome.setOnClickListener(this);
            ImageButton btnGetScreen = (ImageButton) findViewById(R.id.btnGetScreen);
            btnGetScreen.setOnClickListener(this);
            int len = AndroidCameraConfiguration.retrieveCameras().length;
            mVideoWindow = new AndroidVideoWindowImpl(remoteview, localview, new AndroidVideoWindowImpl.VideoWindowListener() {
                @Override
                public void onVideoRenderingSurfaceReady(AndroidVideoWindowImpl vw, SurfaceView surface) {
                    sp.setRemoteVideoWindow(vw);
                    sp.setCameraRotation(rotationToAngle(getWindowManager().getDefaultDisplay().getRotation()));
                    remoteview = surface;
                }

                @Override
                public void onVideoRenderingSurfaceDestroyed(AndroidVideoWindowImpl vw) {
                }

                @Override
                public void onVideoPreviewSurfaceReady(AndroidVideoWindowImpl vw, SurfaceView surface) {
                    localview = surface;
                    sp.setLocalVideoWindow(localview);
                }

                @Override
                public void onVideoPreviewSurfaceDestroyed(AndroidVideoWindowImpl vw) {
                    sp.setLocalVideoWindow(null);
                }
            });

            remoteview.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {


                    switch (event.getAction()) {
                        case MotionEvent.ACTION_DOWN:
                            float x = event.getX();
                            float y = event.getY();

                            break;
                        case MotionEvent.ACTION_UP:
                            x = event.getX();
                            y = event.getY();
                            CmdInfo cmdInfo = new CmdInfo();
                            cmdInfo.sendTapEvent(x, y);
                    }
                    return true;
                }
            });


        }

        tvUsername = (TextView) findViewById(R.id.tvUsername);
        btnHunghp = (ImageButton) findViewById(R.id.btnHungup);
        btnHunghp.setOnClickListener(this);


        tvTime = (TextView) findViewById(R.id.tvTime);
        TextView tvTitle = (TextView) findViewById(R.id.tvTitle);
        tvTitle.setText(getResources().getString(R.string.calling));
        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        String username = bundle.getString("username", "");
        tvUsername.setText(username);
        timerHandler.post(timerRunnable);


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy--->");
        if (mVideoWindow != null)
            mVideoWindow.release();
        timerHandler.removeCallbacks(timerRunnable);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (remoteview != null) {
            ((GLSurfaceView) remoteview).onResume();
            Log.d(TAG, "remoteview onresume2");
        }

        if (mVideoWindow != null) {
            synchronized (mVideoWindow) {
                sp.setRemoteVideoWindow(mVideoWindow);
            }
        }

    }

    @Override
    protected void onPause() {

        if (mVideoWindow != null) {
            synchronized (mVideoWindow) {
                sp.setRemoteVideoWindow(null);
            }
            if (remoteview != null) {
                ((GLSurfaceView) remoteview).onPause();
            }
        }
        super.onPause();
    }
    @Override
    public void onBackPressed() {
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btnHungup:
                sp.terminate(sp.getCurrentCallid());
                this.finish();
                break;
            case R.id.btnGetScreen:
                sp.sendInfo("getscreen", sp.getCurrentCallid());
                break;
            case R.id.btnHome:
                Intent home=new Intent(Intent.ACTION_MAIN);
                home.addCategory(Intent.CATEGORY_HOME);
                startActivity(home);
                break;
            default:
                break;
        }
    }


    static int rotationToAngle(int r) {
        switch (r) {
            case Surface.ROTATION_0:
                return 0;
            case Surface.ROTATION_90:
                return 90;
            case Surface.ROTATION_180:
                return 180;
            case Surface.ROTATION_270:
                return 270;
        }
        return 0;
    }

    private String format(int seconds) {
        int temp = 0;
        StringBuffer sb = new StringBuffer();
        temp = seconds / 3600;
        sb.append((temp < 10) ? "0" + temp + ":" : "" + temp + ":");

        temp = seconds % 3600 / 60;
        sb.append((temp < 10) ? "0" + temp + ":" : "" + temp + ":");

        temp = seconds % 3600 % 60;
        sb.append((temp < 10) ? "0" + temp : "" + temp);

        System.out.println(sb.toString());
        return sb.toString();
    }
    class CallReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            Bundle bundle = intent.getExtras();
            int state = bundle.getInt("state");
            long callid = bundle.getLong("callid");
            switch (state) {
                case SmartphoneState.CallEnd:
                case SmartphoneState.CallReleased:
                    if (callid == sp.getCurrentCallid()) {
                        CallActivity.this.finish();
                    }
                    break;
            }
        }
    }
}
